package vn.edu.hut.soict.translate.wordgraph;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import vn.edu.hut.soict.automaton.MinimalDFABuilder;
import vn.edu.hut.soict.translate.database.TranslatorDatabase;

public class WordGraphMaker {
	private Map<Pair, WordGraph> graphs;
	private Map<Pair, MinimalDFABuilder<Word>> graphBuilders;

	public WordGraphMaker() {
		graphs = new HashMap<Pair, WordGraph>();
		graphBuilders = new HashMap<Pair, MinimalDFABuilder<Word>>();
	}

	public WordGraph[][] build() {
		int maxContentWord = 0;
		int maxFunctionalWord = 0;

		TranslatorDatabase database = new TranslatorDatabase();
		database.connect();
		List<String> sentences = database.getAllVietnameseSentences();
		
		long start = System.currentTimeMillis();
		System.out.print("Start tagging...\n");

		for (String sentence : sentences) {
			Word[] words = WordUtils.split(sentence);
			int contentWord = 0;
			int functionalWord = 0;

			for (int i = 0; i < words.length; i++) {
				if (words[i].isContentWord()) {
					contentWord++;
				}
				else {
					functionalWord++;
				}
			}
			if (contentWord > maxContentWord) {
				maxContentWord = contentWord;
			}
			if (functionalWord > maxFunctionalWord) {
				maxFunctionalWord = functionalWord;
			}

			Pair pair = new Pair(contentWord, functionalWord);
			MinimalDFABuilder<Word> graphBuilder = null;
			if (graphBuilders.containsKey(pair)) {
				graphBuilder = graphBuilders.get(pair);
			}
			else {
				WordGraph graph = new WordGraph();
				graphBuilder = new MinimalDFABuilder<Word>(graph);
				graphs.put(pair, graph);
				graphBuilders.put(pair, graphBuilder);
			}
			graphBuilder.unorederedAdd(words);
		}
		
		long end = System.currentTimeMillis();		
		System.out.printf("... done! [%d sec].\n", (end - start)/1000);

		WordGraph[][] wordGraphs = new WordGraph[maxContentWord + 1][maxFunctionalWord + 1];
		for (int i = 0; i <= maxContentWord; i++) {
			for (int j = 0; j <= maxFunctionalWord; j++) {
				Pair pair = new Pair(i, j);
				if (graphs.containsKey(pair)) {
					wordGraphs[i][j] = graphs.get(pair);
					wordGraphs[i][j].reindex();
				}
				else {
					wordGraphs[i][j] = null;
				}
			}
		}

		database.disconnect();
		return wordGraphs;
	}

	public static void main(String[] args) {
		WordGraphMaker builder = new WordGraphMaker();
		WordGraph[][] wordGraphs = builder.build();
		WordGraphWriter writer = new WordGraphWriter();
		writer.write(wordGraphs, WordGraph.GRAPH_FILE);
	}
}
